import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';
import 'package:toast/toast.dart';
import 'package:version/version.dart';

/// 程序升级
class UpgradeUtil {
  static Future<AppUpgradeInfo> _newVerInfo(
      UpgradeEntity ver, String apkDownloadUrl) async {
    return AppUpgradeInfo(
      title: '新版本 ${ver.version}',
      contents: ver.contents,
      apkDownloadUrl: apkDownloadUrl,
      force: false,
    );
  }

  static Future<void> appUpgrade({
    @required BuildContext context,
    @required String versionJsonUrl,
    @required String apkDownloadUrl,
    @required String versionNumber,
    bool quietness = true, // 安静升级 不提示
  }) async {
    try {
      Response response = await Dio().get(versionJsonUrl);
      if (response.statusCode != 200) {
        Toast.show("读取新版本出错!", context,
            duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
        return;
      }

      UpgradeEntity newVer = UpgradeEntity.fromMap(response.data);
      Version currentVersion = Version.parse(versionNumber);
      Version latestVersion = Version.parse(newVer.version);

      if (latestVersion <= currentVersion) {
        if (quietness == false) {
          Toast.show("当前已是最新版", context,
              duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
        }
        return;
      }

      AppUpgrade.appUpgrade(
        context,
        _newVerInfo(newVer, apkDownloadUrl),
        cancelText: '取消',
        okText: '马上升级!',
        // iosAppId: 'id88888888',
        // appMarketInfo: AppMarket.huaWei,
        onCancel: () {
          // print('onCancel');
        },
        onOk: () {
          // print('onOk');
        },
        downloadProgress: (count, total) {
          // print('count:$count,total:$total');
        },
        downloadStatusChange: (DownloadStatus status, {dynamic error}) {
          // print('status:$status,error:$error');
        },
      );
    } catch (err) {
      print(err);
    }
  }
}

class UpgradeEntity {
  UpgradeEntity({
    this.version,
    this.contents,
  });

  String version;
  List<String> contents;

  UpgradeEntity copyWith({
    int version,
    String title,
    List<String> contents,
  }) =>
      UpgradeEntity(
        version: version ?? this.version,
        contents: contents ?? this.contents,
      );

  factory UpgradeEntity.fromJson(String str) =>
      UpgradeEntity.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory UpgradeEntity.fromMap(Map<String, dynamic> json) => UpgradeEntity(
        version: json["version"] == null ? null : json["version"],
        contents: json["contents"] == null
            ? null
            : List<String>.from(json["contents"].map((x) => x)),
      );

  Map<String, dynamic> toMap() => {
        "version": version == null ? null : version,
        "contents": contents == null
            ? null
            : List<dynamic>.from(contents.map((x) => x)),
      };
}
